<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="结算年月">
              <a-month-picker v-model="queryParam.years" placeholder="请选择" style="width: 100%" valueFormat="yyyy-MM" />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="代理商名称">
              <a-input v-model="queryParam.agentName" placeholder="请输入" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="客户名称">
              <!-- <a-select v-model="queryParam.customId" placeholder="请选择" showSearch :filterOption="filterOption">
                <a-select-option v-for="item in customList" :key="item.id" :value="item.id">{{
                  item.customName
                }}</a-select-option>
              </a-select> -->
              <a-input v-model="queryParam.customName" placeholder="请输入" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="结算方式">
              <a-select v-model="queryParam.settlementMethod" placeholder="请选择" showSearch :filterOption="filterOption">
                <a-select-option value="2">分成</a-select-option>
                <a-select-option value="1">包干</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleOpen('add')" type="primary" icon="plus">新增</a-button>
      <a-button @click="handleImportOpen" type="primary" icon="vertical-align-bottom">导入</a-button>
      <a-button @click="handleImport" type="primary" icon="vertical-align-bottom" :loading="importLoading">导出</a-button>
      <a-button @click="handleCreateImg" type="primary" icon="highlight">生成图片</a-button>
      <a-button @click="handleBatchDel" type="danger" icon="highlight"
        :disabled="selectedRowKeys.length === 0">批量删除</a-button>
    </div>
    <div>
      <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div> -->

      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns"
        :dataSource="dataSource" :pagination="ipagination" :loading="loading" class="j-table-force-nowrap"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, preserveSelectedRowKeys: false, onSelect: handleRowSelect }"
        @change="handleTableChange">
        <span slot="fileName" slot-scope="text, record">
          <a slot="fileName" :href="record.url" target="_blank">{{ text }}</a>
        </span>
        <span slot="settlementMethod" slot-scope="text, record">
          {{ text === '1' ? '包干' : '分成' }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handleOpen('edit', record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleAuto(record)">自动结算生成收益</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a style="color: red;">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <a-modal :title="type === 'add' ? '新增自动结算收益' : '编辑自动结算收益'" :visible="visible" width="1000px"
      :confirm-loading="confirmLoading" @cancel="handleCancel" @ok="handleSubmit">
      <a-form-model :model="form" ref="formRef" :rules="rules">
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-model-item label="客户名称" prop="customId">
              <a-select v-model="form.customId" placeholder="请选择" showSearch :filterOption="filterOption"
                @change="val => selectChange(val, 'custom')">
                <a-select-option v-for="item in customList" :key="item.id" :value="item.id">{{
                  item.customName
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12"><a-form-model-item label="结算方式" prop="settlementMethod">
              <a-select v-model="form.settlementMethod" placeholder="请选择">
                <a-select-option key="1">包干</a-select-option>
                <a-select-option key="2">分成</a-select-option>
              </a-select>
            </a-form-model-item></a-col>
          <a-col :span="12"><a-form-model-item label="签约价(元/兆瓦时)" prop="contractPrice">
              <a-input-number v-model="form.contractPrice" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '1'"><a-form-model-item label="包干价(元/兆瓦时)"
              prop="intermediateMinimumPrice">
              <a-input-number v-model="form.intermediateMinimumPrice" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '1'"><a-form-model-item label="包干收益(元/兆瓦时)"
              prop="intermediateConditions">
              <a-input-number v-model="form.intermediateConditions" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '2'"><a-form-model-item label="当月批发成本价(元/兆瓦时)"
              prop="wholesaleCostPrice">
              <a-input-number v-model="form.wholesaleCostPrice" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '2'"><a-form-model-item label="保函分摊(元/兆瓦时)"
              prop="guaranteeAllocation">
              <a-input-number v-model="form.guaranteeAllocation" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '2'"><a-form-model-item label="度电收益(元/兆瓦时)"
              prop="electricityRevenueKilowatt">
              <a-input-number v-model="form.electricityRevenueKilowatt" placeholder="请输入" />
            </a-form-model-item></a-col>
          <a-col :span="12"><a-form-model-item label="当月用电量" prop="quantity">
              <a-input-number v-model="form.quantity" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12" v-if="form.settlementMethod === '2'"><a-form-model-item label="分成收益比例%(元/兆瓦时)"
              prop="profitSharingRatio">
              <a-input-number v-model="form.profitSharingRatio" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12"><a-form-model-item label="固定比例%" prop="fixedPortion">
              <a-input-number v-model="form.fixedPortion" placeholder="请输入" /> </a-form-model-item></a-col>
          <a-col :span="12"><a-form-model-item label="固定部分结算电量" prop="settlementElectricityConsumption">
              <a-input-number v-model="form.settlementElectricityConsumption" placeholder="请输入" style="width: 100%" />
            </a-form-model-item></a-col>
          <a-col :span="12"><a-form-model-item label="结算年月" prop="years">
              <a-month-picker v-model="form.years" placeholder="请选择" style="width: 100%" valueFormat="yyyy-MM" />
            </a-form-model-item></a-col>
          <a-col :span="12">
            <a-form-model-item label="代理商名称" prop="agentId">
              <a-select v-model="form.agentId" placeholder="请选择" showSearch @change="val => selectChange(val, 'agent')">
                <a-select-option v-for="item in agentList" :key="item.id" :value="item.id">{{
                  item.corporateName
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <a-modal :visible="importVisible" title="导入数据" @cancel="importVisible = false">
      <a-spin :spinning="fileUpLoading">
        <h4>模板下载</h4>
        <a-radio-group v-model="templateTab">
          <a-radio-button value="1">包干</a-radio-button>
          <a-radio-button value="2">分成</a-radio-button>
        </a-radio-group><br>
        <a-button v-if="templateTab === '1'" @click="handleImporTemplateDown('bg')" type="link">包干模板</a-button>
        <a-button v-else @click="handleImporTemplateDown('fc')" type="link">分成模板</a-button>
        <h4>文件上传</h4>
        <a-upload v-if="importVisible" name="file" :multiple="true" accept=".xls,.xlsx" :action="actionUrl"
          :data="{ mealType: templateTab }" :headers="{
            'X-Access-Token': $store.state.user.token
          }" @change="handleFileUp">
          <a-button> <a-icon type="upload" /> 上传文件 </a-button>
        </a-upload>
      </a-spin>
    </a-modal>
    <a-modal :visible="imgVisible" title="生成图片" width="800px" okText="保存图片" @ok="handleImgSave"
      @cancel="imgVisible = false" :confirm-loading="imgDownLoading">
      <div class="img_box" v-if="imgVisible">
        <div ref="imgBoxRef" id="autoSettlemenIncomeImg" style="padding: 20px;position: relative;">
          <div class="header"><span>居间费用结算确认书</span> <img src="./logo.jpg" /></div>
          <p style="text-indent: 2rem;">
            居间服务人：<span>{{ imgData.agentName }}</span>
          </p>
          <p>
            现我司（深圳市瑞恒兆能源有限公司）对
            <span>{{ imgData.month }}</span> 月份代理用户结算确认，以下电力用户为居间开发的客户， {{ imgData.type }}模式
            客户具体居间服务费支付标准如下(其中 结算电量以结算协议约定电量部分为准)
          </p>
          <a-table :columns="columns2" :dataSource="imgData.tableList" bordered :pagination="false"></a-table>
          <p style="margin-top: 26px;">
            <span>{{ imgData.month }}</span> 月份税前总收益
            <span style="padding-left: 20px;">{{ imgData.all }} 元</span>
          </p>
          <p>本期开专用发票金额（1%） {{ imgData.one }} 元</p>
          <p>本期开专用发票金额（3%） {{ imgData.three }} 元</p>
          <p>本期开专用发票金额（6%） {{ imgData.six }} 元</p>
          <p>
            以上数据为贵公司 <span>{{ imgData.month }}</span>
            月份代理电力用户结算收益，如确认无异议请按照结算金额进行开具对应税点发票。未经我公司许可，贵公司不得向第三方提供（披露）结算相关内容，否则我公司有权追究贵公司相关责任。
          </p>
          <p>我司承诺将根据双方签订的合同及本确认书相关条款进行居间费用的支付。如有疑问请联系我司。</p>
        </div>
      </div>
    </a-modal>
    <a-modal :visible="imgVisible2" title="生成图片" width="800px" okText="保存图片" @ok="handleImgSave2"
      @cancel="imgVisible2 = false" :confirm-loading="imgDownLoading">
      <div class="img_box" v-if="imgVisible2">
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane :key="key" :tab="key" v-for="(item, key, index) in imgData2">
            <div :id="'autoSettlemenIncomeImg' + index" style="padding: 20px;position: relative;">
              <div class="header"><span>居间费用结算确认书</span> <img src="./logo.jpg" /></div>
              <p style="text-indent: 2rem;">
                居间服务人：<span>{{ item.agentName }}</span>
              </p>
              <p>
                现我司（深圳市瑞恒兆能源有限公司）对
                <span>{{ item.month }}</span> 月份代理用户结算确认，以下电力用户为居间开发的客户， {{ item.type }}模式
                客户具体居间服务费支付标准如下(其中 结算电量以结算协议约定电量部分为准)
              </p>
              <a-table :columns="columns2" :dataSource="item.table" bordered :pagination="false"></a-table>
              <p style="margin-top: 26px;">
                <span>{{ item.month }}</span> 月份税前总收益
                <span style="padding-left: 20px;">{{ item.all }} 元</span>
              </p>
              <p>本期开专用发票金额（1%） {{ item.one }} 元</p>
              <p>本期开专用发票金额（3%） {{ item.three }} 元</p>
              <p>本期开专用发票金额（6%） {{ item.six }} 元</p>
              <p>
                以上数据为贵公司 <span>{{ item.month }}</span>
                月份代理电力用户结算收益，如确认无异议请按照结算金额进行开具对应税点发票。未经我公司许可，贵公司不得向第三方提供（披露）结算相关内容，否则我公司有权追究贵公司相关责任。
              </p>
              <p>我司承诺将根据双方签订的合同及本确认书相关条款进行居间费用的支付。如有疑问请联系我司。</p>
            </div>
          </a-tab-pane>
        </a-tabs>

      </div>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { apiAdd, apiEdit, apiGeCustomList, apiAutoSettlemenIncome, apiDel, apiImport, apiBatchDel } from '@/api/contractManage/autoSettlemenIncome'
import { postAction } from '@/api/manage'
import { apiGetAgentList } from '@/api/contractManage/agentIncome'
import { weaterMaskCanvasFn } from './sy'
import html2canvas from 'html2canvas'
import Decimal from 'decimal.js'
import { Watermark } from 'watermark-js-plus'
let watermarkInstace = null
export default {
  name: 'PolicyDoc',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      // description: '政策文档管理',
      // 表头
      //、、、、、、保函分摊、
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '电力用户名称',
          align: 'center',
          dataIndex: 'customName'
        },
        {
          title: '结算方式',
          align: 'center',
          dataIndex: 'settlementMethod',
          scopedSlots: { customRender: 'settlementMethod' }
        },
        {
          title: '代理商名称',
          align: 'center',
          dataIndex: 'agentName'
        },
        {
          title: '结算年月',
          align: 'center',
          dataIndex: 'years'
        },
        {
          title: '当月电量',
          align: 'center',
          dataIndex: 'quantity'
        },
        {
          title: '签约价',
          align: 'center',
          dataIndex: 'contractPrice'
        },
        {
          title: '包干价',
          align: 'center',
          dataIndex: 'intermediateMinimumPrice'
        },
        {
          title: '包干收益',
          align: 'center',
          dataIndex: 'intermediateConditions'
        },
        {
          title: '固定比例',
          align: 'center',
          dataIndex: 'fixedPortion'
        },
        {
          title: '固定部分结算电量',
          align: 'center',
          dataIndex: 'settlementElectricityConsumption'
        },

        {
          title: '分成收益比例',
          align: 'center',
          dataIndex: 'profitSharingRatio'
        },
        {
          title: '度电收益',
          align: 'center',
          dataIndex: 'electricityRevenueKilowatt'
        },
        {
          title: '批发成本价',
          align: 'center',
          dataIndex: 'wholesaleCostPrice'
        },
        {
          title: '保函分摊',
          align: 'center',
          dataIndex: 'guaranteeAllocation'
        },
        {
          title: '代理税前收益',
          align: 'center',
          dataIndex: 'intermediateAmount'
        },
        {
          title: '代理商1',
          align: 'center',
          dataIndex: 'agentNameOne'
        },
        {
          title: '代理1度电收益(元/兆瓦时）',
          align: 'center',
          dataIndex: 'intermediaryAgentOneQuantity'
        },
        {
          title: '代理1税前收益',
          align: 'center',
          dataIndex: 'intermediateAmountOne'
        },
        {
          title: '代理商2',
          align: 'center',
          dataIndex: 'intermediaryAgentTwo'
        },
        {
          title: '代理2度电收益(元/兆瓦时）',
          align: 'center',
          dataIndex: 'intermediaryAgentTwoQuantity'
        },
        {
          title: '代理2税前收益',
          align: 'center',
          dataIndex: 'intermediateAmountTwo'
        },
        {
          title: '代理商3',
          align: 'center',
          dataIndex: 'intermediaryAgentThree'
        },
        {
          title: '代理3度电收益(元/兆瓦时）',
          align: 'center',
          dataIndex: 'intermediaryAgentThreeQuantity'
        },
        {
          title: '代理3税前收益',
          align: 'center',
          dataIndex: 'intermediateAmountThree'
        },
        {
          title: '代理商4',
          align: 'center',
          dataIndex: 'intermediaryAgentFour'
        },
        {
          title: '代理4度电收益(元/兆瓦时）',
          align: 'center',
          dataIndex: 'intermediaryAgentFourQuantity'
        },
        {
          title: '代理4税前收益',
          align: 'center',
          dataIndex: 'intermediateAmountFour'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 240,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'sort',
          width: 80,
          align: 'center'
        },
        {
          title: '代理电力用户名称',
          align: 'center',
          dataIndex: 'customName'
        },
        {
          title: '固定结算电量（兆瓦时）',
          align: 'center',
          dataIndex: 'settlementElectricityConsumption'
        },
        {
          title: '代理税前收益(元)',
          align: 'center',
          dataIndex: 'intermediateAmount'
        }
      ],
      url: {
        list: '/agentSettlement/list'
      },
      submitLoad: false,
      addFormDataList: [
        {
          agentId: undefined,
          agentName: undefined,
          quantity: undefined,
          years: undefined,
          transaction: undefined,
          fileList: []
        }
      ],
      form: {
        settlementMethod: '1'
      },
      type: 'add',
      confirmLoading: false,
      customList: [],
      visible: false,
      agentList: [],
      rules: {
        customId: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
        agentId: [{ required: true, message: '请选择代理商名称', trigger: 'change' }],
        settlementMethod: [{ required: true, message: '请选择结算方式', trigger: 'change' }],
        contractPrice: [{ required: true, message: '请输入签约价(元/兆瓦时)', trigger: 'blur' }],
        intermediateMinimumPrice: [{ required: true, message: '请输入包干价(元/兆瓦时)', trigger: 'blur' }],
        wholesaleCostPrice: [{ required: true, message: '请输入当月批发成本价(元/兆瓦时)', trigger: 'blur' }],
        guaranteeAllocation: [{ required: true, message: '请输入保函分摊(元/兆瓦时)', trigger: 'blur' }],
        electricityRevenueKilowatt: [{ required: true, message: '请输入度电收益(元/兆瓦时)', trigger: 'blur' }],
        quantity: [{ required: true, message: '请输入当月用电量', trigger: 'blur' }],
        profitSharingRatio: [{ required: true, message: '请输入分成收益比例(元/兆瓦时)', trigger: 'blur' }],
        fixedPortion: [{ required: true, message: '请输入固定比例', trigger: 'blur' }],
        settlementElectricityConsumption: [{ required: true, message: '请输入固定部分结算电量', trigger: 'blur' }],
        years: [{ required: true, message: '请选择结算年月', trigger: 'change' }],
        intermediateConditions: [{ required: true, message: '请输入包干收益', trigger: 'blur' }]
      },
      importVisible: false,
      fileUpLoading: false,
      templateTab: '1',
      imgVisible: false,
      imgVisible2: false,
      imgData: {
        month: 1,
        agentName: '',
        tableList: [],
        one: '',
        three: '',
        six: '',
        type: '',
        all: ''
      },
      imgData2: {},
      imgDownLoading: false,
      importLoading: false
    }
  },
  computed: {
    actionUrl() {
      return process.env.VUE_APP_API_BASE_URL + '/agentSettlement/pointsImport'
    }
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      params.field = undefined
      this.loading = true
      console.log(params, 'params');
      postAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 过滤
    filterOption(value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
    // 获取客户
    async getUserList() {
      const { code, result } = await apiGeCustomList()
      if (code === 200) {
        this.customList = result.records || []
      }
    },
    //获取代理商
    async getAgentList() {
      const { code, result } = await apiGetAgentList()
      if (code === 0) {
        this.agentList = result.records || []
      }
    },
    // 下拉带入名称
    selectChange(val, type) {
      if (type === 'custom') {
        if (val) {
          this.form.customId = val
          this.form.customName = this.customList.find(item => item.id === val).customName
        } else {
          this.form.customId = undefined
          this.form.customName = undefined
        }
      } else if (type === 'agent') {
        if (val) {
          this.form.agentId = val
          this.form.agentName = this.agentList.find(item => item.id === val).corporateName
        } else {
          this.form.agentId = undefined
          this.form.agentName = undefined
        }
      }
    },
    handleOpen(type, row) {
      if (type === 'edit') {
        this.form = JSON.parse(JSON.stringify(row))
      } else {
        this.form = {}
      }
      this.type = type
      this.visible = true
    },
    // 自动结算收益
    handleAuto(row) {
      apiAutoSettlemenIncome(row)
        .then(res => {
          if (res.code === 200) {
            this.loadData()
            this.$message.success('操作成功！')
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => { })
    },
    handleCancel() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.visible = false
    },
    async handleSubmit() {
      await this.$refs.formRef.validate()
      this.confirmLoading = true
      let apiFun = this.type === 'add' ? apiAdd : apiEdit
      apiFun(this.form)
        .then(res => {
          if (res.code === 200) {
            this.handleCancel()
            this.loadData()
            this.selectedRowKeys = []
            this.selectionRows = []
            this.allPageSelected = {}
            this.$message.success('操作成功！')
          } else {
            this.$message.error(res.message)
          }
          console.log(res)
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleImportOpen() {
      this.importVisible = true
    },
    handleImporTemplateDown(type) {
      this.fileUpLoading = true
      var a = document.createElement('a') //创建一个<a></a>标签
      a.href = `/static/${type}.xls` // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = `${type === 'bg' ? '包干模板' : '分成模板'}.xls` //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
      a.style.display = 'none' // 障眼法藏起来a标签
      document.body.appendChild(a) // 将a标签追加到文档对象中
      a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove() // 一次性的，用完就删除a标签
      this.fileUpLoading = false
    },
    handleFileUp({ file }) {
      const { status, response } = file
      if (status === 'uploading') {
        this.fileUpLoading = true
      }
      if (status === 'done' || status === 'error ') {
        this.fileUpLoading = false
      }
      if (status === 'done') {
        const { code, result, message } = response
        if (code === 200) {
          this.$message.success('导入成功！')
          this.importVisible = false
          this.loadData()
          this.selectedRowKeys = []
          this.selectionRows = []
          this.allPageSelected = {}
        } else {
          this.$message.error(message)
        }
      }
    },
    handleImgCancel() {
      watermarkInstace.destroy()
      this.imgVisible = false
    },
    encryptPhoneNumber() {
      let phone = this.$store.state.user.info.phone
      if (typeof phone !== 'string') {
        phone = phone.toString()
      }
      if (phone.length !== 11) {
        return phone
      }
      return phone.slice(0, 3) + '****' + phone.slice(-4)
    },
    handleCreateImg() {
      let copyList = Object.values(this.allPageSelected)
      if (copyList.length === 0) {
        return this.$message.warning('请选择数据！')
      }
      copyList = copyList.map((item, index) => {
        item.sort = index + 1
        return item
      })
      let agentName = copyList[0]['agentName']
      // 1.只有单个代理商
      if (agentName) {
        if (copyList.some(item => item.agentName !== agentName)) {
          return this.$message.warning('请选择相同代理人！')
        }
        let sum1 = this.sumProperty(copyList, 'settlementElectricityConsumption', 6)
        let sum2 = this.sumProperty(copyList, 'intermediateAmount', 2)
        let one = Decimal(sum2)
          .div(Decimal(1.13))
          .mul(Decimal(1.01))
          .toFixed(2)
        let three = Decimal(sum2)
          .div(Decimal(1.13))
          .mul(Decimal(1.03))
          .toFixed(2)
        let six = Decimal(sum2)
          .div(Decimal(1.13))
          .mul(Decimal(1.06))
          .toFixed(2)
        let lastRow = {
          sort: '合计',
          customName: copyList.length + '户',
          settlementElectricityConsumption: sum1,
          intermediateAmount: sum2
        }
        let type = copyList.every(item => item.settlementMethod === '1')
          ? '包干'
          : copyList.every(item => item.settlementMethod === '2')
            ? '分成'
            : '包干/分成'
        this.imgData = {
          agentName,
          month: copyList[0]['years'].split('-')[1],
          tableList: copyList.concat(lastRow),
          one,
          three,
          six,
          type,
          all: sum2
        }
        this.imgVisible = true
        this.$nextTick(() => {
          let phone = copyList[0]['phone']
          let agentNameNew = copyList[0]['agentNameNew']
          if (typeof phone === 'string' && phone.length === 11) {
            phone = phone.slice(0, 3) + '****' + phone.slice(-4)
          }
          watermarkInstace = new Watermark({
            parent: '#autoSettlemenIncomeImg',
            contentType: 'rich-text',
            globalAlpha: 0.3,
            content: `<div>
            <div> ${agentNameNew}</div>
            <div> ${phone}</div>
            </div>`,
            fontSize: '12px',
            height: 200,
            shadowStyle: {
              shadowBlur: 10,
              shadowColor: '#000000FF',
              shadowOffsetX: 0,
              shadowOffsetY: 0
            },
            onSuccess: () => {
              // success callback
            }
          })
          watermarkInstace.create()
        })
      } else {
        // 2.多个代理商
        // 第一条数据的代理商列表，然后每条数据去对比是否有相同代理商
        let imgDataList = {}
        let dlsList = []
        if (copyList[0]['agentNameOne']) {
          dlsList.push(copyList[0]['agentNameOne'])
        }
        if (copyList[0]['intermediaryAgentTwo']) {
          dlsList.push(copyList[0]['intermediaryAgentTwo'])
        }
        if (copyList[0]['intermediaryAgentThree']) {
          dlsList.push(copyList[0]['intermediaryAgentThree'])
        }
        if (copyList[0]['intermediaryAgentFour']) {
          dlsList.push(copyList[0]['intermediaryAgentFour'])
        }
        let flag = false
        for (let index = 1; index < copyList.length; index++) {
          const element = array[index];
          flag = dlsList.every(item => item === element.agentNameOne || item === element.intermediaryAgentTwo || item === element.intermediaryAgentThree || item === element.intermediaryAgentFour)
        }
        if (!flag) {
          return this.$message.warning('请选择相同代理人！')
        }
        for (let index = 0; index < copyList.length; index++) {
          const element = array[index];
          let oneName = element['agentNameOne']
          let twoName = element['intermediaryAgentTwo']
          let threeName = element['intermediaryAgentThree']
          let fourName = element['intermediaryAgentFour']
          if (oneName) {
            if (Array.isArray(imgDataList[oneName])) {
              imgDataList[oneName]['table'].push(element)
            } else {
              imgDataList[oneName] = {
                table: [element]
              }
            }
          }
          if (twoName) {
            if (Array.isArray(imgDataList[twoName])) {
              imgDataList[twoName]['table'].push(element)
            } else {
              imgDataList[twoName] = {
                table: [element]
              }
            }
          }
          if (threeName) {
            if (Array.isArray(imgDataList[threeName])) {
              imgDataList[threeName]['table'].push(element)
            } else {
              imgDataList[threeName] = {
                table: [element]
              }
            }
          }
          if (fourName) {
            if (Array.isArray(imgDataList[fourName])) {
              imgDataList[fourName]['table'].push(element)
            } else {
              imgDataList[fourName] = {
                table: [element]
              }
            }
          }
        }
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            const element = object[key];
            console.log(element, 'element');
            let sum1 = this.sumProperty(element['table'], 'settlementElectricityConsumption', 6)
            let sum2 = this.sumProperty(element['table'], 'intermediateAmount', 2)
            let one = Decimal(sum2)
              .div(Decimal(1.13))
              .mul(Decimal(1.01))
              .toFixed(2)
            let three = Decimal(sum2)
              .div(Decimal(1.13))
              .mul(Decimal(1.03))
              .toFixed(2)
            let six = Decimal(sum2)
              .div(Decimal(1.13))
              .mul(Decimal(1.06))
              .toFixed(2)
            let lastRow = {
              sort: '合计',
              customName: element['table'].length + '户',
              settlementElectricityConsumption: sum1,
              intermediateAmount: sum2
            }
            let type = element['table'].every(item => item.settlementMethod === '1')
              ? '包干'
              : element['table'].every(item => item.settlementMethod === '2')
                ? '分成'
                : '包干/分成'
            element.month = element['table'][0]['years'].split('-')[1]
            element.one = one
            element.three = three
            element.six = six
            element.type = type
            element.table = element['table'].concat(lastRow)
            element.all = sum2
            this.imgVisible2 = true
            this.$nextTick(() => {
              let phone = element['table'][0]['phone']
              let agentNameNew = element['table'][0]['agentNameNew']
              if (typeof phone === 'string' && phone.length === 11) {
                phone = phone.slice(0, 3) + '****' + phone.slice(-4)
              }
              let index = Object.keys(imgDataList).findIndex(item => item === key)
              watermarkInstace = new Watermark({
                parent: '#autoSettlemenIncomeImg' + index,
                contentType: 'rich-text',
                globalAlpha: 0.3,
                content: `<div>
            <div> ${agentNameNew}</div>
            <div> ${phone}</div>
            </div>`,
                fontSize: '12px',
                height: 200,
                shadowStyle: {
                  shadowBlur: 10,
                  shadowColor: '#000000FF',
                  shadowOffsetX: 0,
                  shadowOffsetY: 0
                },
                onSuccess: () => {
                  // success callback
                }
              })
              watermarkInstace.create()
            })
          }
        }
      }


    },
    handleImgSave() {
      this.imgDownLoading = true
      html2canvas(this.$refs['imgBoxRef']).then(canvas => {
        let dataURL = canvas.toDataURL('image/png') //base64格式的图片 url
        // 创建a标签下载图片
        var addElement = document.createElement('a')
        addElement.href = dataURL
        addElement.download = '下载.png' //设置下载的图片名称
        document.body.appendChild(addElement)
        addElement.click()
        document.body.removeChild(addElement)
        this.imgDownLoading = false
      })
    },
    sumProperty(array, property, len) {
      let sum = Decimal(0)
      for (let i = 0; i < array.length; i++) {
        const value = parseFloat(array[i][property])
        sum = sum.add(Decimal(value || 0))
      }
      return sum.toFixed(len || 2)
    },
    handleDelete(id) {
      apiDel({ id }).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功！')
          this.loadData()
          this.selectedRowKeys = []
          this.selectionRows = []
          this.allPageSelected = {}
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleImport() {
      this.importLoading = true
      apiImport(this.getQueryParams()).then(data => {
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '自动结算收益导出.xlsx') //下载后文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) //下载完成移除元素
        window.URL.revokeObjectURL(url) //释放掉blob对象
        this.importLoading = false
      }).catch(() => {
        this.importLoading = false
      })
    },
    handleBatchDel() {
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: () => {
          apiBatchDel({ ids: this.selectedRowKeys }).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功！')
              this.searchQuery()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      });
    },
  },
  created() {
    this.getUserList()
    this.getAgentList()
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.ant-input-number {
  width: 100%;
}

.img_box {
  max-height: 62vh;
  overflow-y: auto;

  .header {
    text-align: center;
    position: relative;

    span {
      padding-left: 120px;
      font-size: 26px;
      font-weight: bold;
    }

    img {
      position: relative;
      left: 100px;
      width: 120px;
    }
  }

  p {
    text-indent: 2rem;
    font-size: 16px;
    line-height: 24px;
    /* span {
      font-weight: bold;
    } */
  }
}
</style>
